package com.bgds.sys.module.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bgds.sys.common.pagevo.Result;
import com.bgds.sys.common.pagevo.SeriesVo;
import com.bgds.sys.common.utils.DateUtils;
import com.bgds.sys.common.utils.ResultUtil;
import com.bgds.sys.influx.service.InfluxService;
import com.bgds.sys.module.entity.AlarmLog;
import com.bgds.sys.module.entity.Device;
import com.bgds.sys.module.entity.DeviceDynamicAttr;
import com.bgds.sys.module.entity.dto.AlarmDeviceDto;
import com.bgds.sys.module.entity.dto.AlarmLogDto;
import com.bgds.sys.module.service.IDeviceDynamicAttrService;
import com.bgds.sys.module.service.IDeviceService;
import com.bgds.sys.module.service.IAlarmLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lj
 */
@Slf4j
@RestController
@Api(tags = "综合看板接口")
@RequestMapping("/synthesizeBoard")
public class SynthesizeBoardController {

    @Autowired
    private IAlarmLogService iAlarmLogService;
    @Autowired
    private IDeviceService iDeviceService;

    @Autowired
    private IDeviceDynamicAttrService iDeviceDynamicAttrService;
    @Autowired
    private InfluxService influxService;

    @RequestMapping(value = "/deviceStateData", method = RequestMethod.GET)
    @ApiOperation(value = "设备状态监测数据",notes = "设备状态监测数据",httpMethod = "GET")
    public Result<Map<String,Integer>> getDeviceStatusData(){
        Map<String,Integer> map=new HashMap<>(10);
        //设备总数
        List<Device> devices= iDeviceService.listPageDevice();
        map.put("totalCount",devices.size());
        //异常总数
        List<AlarmLog> abnormalLogs= iAlarmLogService.unhandleLog();
        Integer abnormalCount=0;
        if(CollectionUtil.isNotEmpty(abnormalLogs)){
            Map<String,List<AlarmLog>> logMap= abnormalLogs.stream().collect(Collectors.groupingBy(log -> log.getDeviceCode() ));
            for(String deviceCode:logMap.keySet()){
               Optional<Device> device= devices.stream().filter(d->d.getDeviceCode().equals(deviceCode)).findAny();
               if(device!=null){
                   abnormalCount+=1;
               }
            }
        }
        map.put("abnormalCount",abnormalCount);
        //正常总数
        int normalCount= devices.size()-abnormalCount;
        map.put("normalCount",normalCount);
        return new ResultUtil<Map<String,Integer>>().setData(map);
    }

    @RequestMapping(value = "/alarmDevices", method = RequestMethod.GET)
    @ApiOperation(value = "最近报警设备列表",notes = "最近报警设备列表",httpMethod = "GET")
    public Result<List<AlarmDeviceDto> > getCurrentWarnDevices(){
       List<AlarmDeviceDto> alarmDeviceDtos = iAlarmLogService.nearest2HourAlarmDevices();
        return new ResultUtil<List<AlarmDeviceDto> >().setData(alarmDeviceDtos);

    }

    @RequestMapping(value = "/alarmLogTimes", method = RequestMethod.GET)
    @ApiOperation(value = "最近报警信息及报警次数",notes = "最近报警信息及报警次数",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNumber", dataType = "Integer", value = "页码"),
            @ApiImplicitParam(name = "pageSize", dataType = "Integer", value = "页大小"),
    })
    public Result<Map<String,Object>> getCurrentWarnLog( Integer pageNumber,Integer pageSize){

        Map<String,Object> map=new HashMap<>(10);
        //统计过去两个小时报警次数
        String before2Time=DateUtils.getBeforeByHourTime(2);
        String currentTime=DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
        Integer count= iAlarmLogService.count2Hour(before2Time,currentTime);
        map.put("times",count);
        //最近报警日志
        IPage<AlarmLogDto> alarmLogs = iAlarmLogService.nearest2HourAlarmLog(pageNumber,pageSize);
        map.put("alarmLogs", alarmLogs);
        return new ResultUtil<Map<String,Object>>().setData(map);
    }

    @RequestMapping(value = "/trend", method = RequestMethod.GET)
    @ApiOperation(value = "根据报警点获取趋势数据",notes = "根据报警点获取趋势数据",httpMethod = "GET",response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "attrId", dataType = "Long", value = "报警点Id"),
            @ApiImplicitParam(name = "alarmDate", dataType = "Long", required = true,value = "报警时间"),
    })

    public Result<List<SeriesVo>> getChartDataByDeviceAttrCode(Long attrId, Long alarmDate){
        DeviceDynamicAttr dynamicAttr= iDeviceDynamicAttrService.getById(attrId);
        List<DeviceDynamicAttr> deviceDynamicAttrs=new ArrayList<>();
        deviceDynamicAttrs.add(dynamicAttr);
        Date endTime=new Date(alarmDate);
        Long startTime=DateUtils.getBeforeTimeInMillis(endTime,2);
        List<SeriesVo>  chartData= influxService.queryByForMap(dynamicAttr.getDeviceCode(),startTime,alarmDate,deviceDynamicAttrs);
        chartData.forEach(item -> item.setUnit(dynamicAttr.getUnit()));
        return new ResultUtil<List<SeriesVo>>().setData(chartData);
    }

}
